package com.adminserver.controller;

import cn.hutool.core.util.ObjectUtil;
import com.adminserver.customEntity.EditUserPermissionEntity;
import com.adminserver.customEntity.SystemAccountEntity;
import com.adminserver.customEntity.UnionUserRoleEntity;
import com.adminserver.entity.*;
import com.adminserver.mapper.UserPermissionMapper;
import com.adminserver.mapper.UserRoleMapper;
import com.adminserver.service.*;
import com.adminserver.util.FormatUserRoleData;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    RolePermissionService rolePermissionService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    UserPermissionMapper userPermissionMapper;

    @Autowired
    SystemAccountEntity systemAccountEntity;

    @GetMapping("/pullRoleAndPermission")
    public ResponseUtil pullRoleAndPermission() {

        List<PermissionEntity> permissionEntities = permissionService.list();
        List<RolePermissionEntity> rolePermissionEntities = rolePermissionService.list();

        Map result = new HashMap();
        result.put("permissionEntities", permissionEntities);
        result.put("rolePermissionEntities", rolePermissionEntities);
        return ResponseUtil.setE(ResponseEnum.OK).setData(result);
    }

    @GetMapping("/pullRole")
    public ResponseUtil pullRole() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(roleService.list());
    }

    @GetMapping("/addRole")
    public ResponseUtil addRole(@RequestParam String role) {
        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setRoleName(role);
        roleService.save(roleEntity);
        return ResponseUtil.setE(ResponseEnum.OK).setData(roleEntity.getRoleId());
    }

    @GetMapping("/delRole")
    public ResponseUtil delRole(@RequestParam String roleId) {
        roleService.removeById(roleId);
        return ResponseUtil.setE(ResponseEnum.OK);
    }

    @GetMapping("/pullPermission")
    public ResponseUtil pullPermission() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(permissionService.list());
    }

    @GetMapping("/addPermission")
    public ResponseUtil addPermission(@RequestParam String permission) {
        PermissionEntity permissionEntity = new PermissionEntity();
        permissionEntity.setPermName(permission);
        permissionService.save(permissionEntity);
        return ResponseUtil.setE(ResponseEnum.OK).setData(permissionEntity.getPermId());
    }

    @Transactional
    @GetMapping("/delPermission")
    public ResponseUtil delPermission(@RequestParam String permId) {
        try {
            permissionService.removeById(permId);
            LambdaQueryWrapper<UserPermissionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserPermissionEntity::getPermissionId, permId);
            userPermissionService.remove(lambdaQueryWrapper);
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("权限删除成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("权限删除失败, 请刷新重试");
        }
    }

    @GetMapping("/pullRolePermission")
    public ResponseUtil pullRolePermission() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(rolePermissionService.list());
    }

    @Transactional
    @PostMapping("/addRolePermission")
    public ResponseUtil addRolePermission(@RequestBody Map data) {
        String roleId = data.get("roleId").toString();
        List<String> array = JSON.parseArray(data.get("permissionId").toString(), String.class);
        ArrayList<RolePermissionEntity> arrayList = new ArrayList<>();
        for (String id : array) {
            RolePermissionEntity entity = new RolePermissionEntity();
            entity.setRoleId(roleId);
            entity.setPermissionId(id);
            arrayList.add(entity);
        }
        try {
            LambdaQueryWrapper<RolePermissionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(RolePermissionEntity::getRoleId, roleId);
            rolePermissionService.remove(lambdaQueryWrapper);
            rolePermissionService.saveBatch(arrayList);
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("授权失败，请核对后重试");
        }
    }


    public List<String> getSetKey(HashSet<UnionUserRoleEntity> hashSet) {
        List<String> userIds = new ArrayList<>();
        for (UnionUserRoleEntity entity : hashSet) {
            userIds.add(entity.getUserId());
        }
        return userIds;
    }

    @GetMapping("/pullUserRole")
    public ResponseUtil pullUserRole(@RequestParam(defaultValue = "1") int current,
                                     @RequestParam(defaultValue = "100") int size) {
        Page<UserRoleEntity> page = new Page<>(current, size);
        userRoleService.page(page);
        List<UserRoleEntity> records = page.getRecords();
        String[] userIds = new String[(int) page.getTotal()];
        for (int i = 0; i < records.size(); i++) {
            userIds[i] = records.get(i).getUserId();
        }

        HashSet<UnionUserRoleEntity> unionUserRoleEntities = FormatUserRoleData.formatUserRole(userRoleMapper.selectAllUserRole(userIds, null, null));
        List<UserPermissionEntity> userPermissionEntities = userPermissionMapper.queryLimitUserPermissionByUserIds(getSetKey(unionUserRoleEntities));
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", userPermissionEntities.size());
        map.put("records", FormatUserRoleData.checkLimitPermission(userPermissionEntities, unionUserRoleEntities));
        return ResponseUtil.setE(ResponseEnum.OK).setData(map);
    }

    /**
     * 开启/禁用 用户角色权限
     *
     * @param entity
     * @return
     */
    @PostMapping("/toggleRole")
    public ResponseUtil toggleRole(@RequestBody UserRoleEntity entity) {
        if (entity.getUserId().equals(systemAccountEntity.getAccount())){
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("非法操作, 禁权系统账号");
        }
        LambdaUpdateWrapper<UserRoleEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserRoleEntity::getUserId, entity.getUserId());
        lambdaUpdateWrapper.eq(UserRoleEntity::getRoleId, entity.getRoleId());
        lambdaUpdateWrapper.set(UserRoleEntity::isEnabled, !entity.isEnabled());
        return ResponseUtil.setE(ResponseEnum.OK).setData(userRoleService.update(lambdaUpdateWrapper));
    }

    @GetMapping("/queryByUserId")
    public ResponseUtil queryByUserId(@RequestParam String userId) {
        if (ObjectUtil.isEmpty(userId)) return ResponseUtil.setE(ResponseEnum.OK);
        HashSet<UnionUserRoleEntity> unionUserRoleEntities = FormatUserRoleData.formatUserRole(userRoleMapper.selectAllUserRole(new String[]{userId}, null, null));
        List<UserPermissionEntity> userPermissionEntities = userPermissionMapper.queryLimitUserPermissionByUserIds(getSetKey(unionUserRoleEntities));
        return ResponseUtil.setE(ResponseEnum.OK).setData(FormatUserRoleData.checkLimitPermission(userPermissionEntities, unionUserRoleEntities));
    }

    @PostMapping("/queryByURoleId")
    public ResponseUtil queryByURoleId(@RequestBody String[] roleIds) {
        if (ObjectUtil.isEmpty(roleIds)) return ResponseUtil.setE(ResponseEnum.OK);
        HashSet<UnionUserRoleEntity> unionUserRoleEntities = FormatUserRoleData.formatUserRole(userRoleMapper.selectAllUserRole(null, roleIds, null));
        List<UserPermissionEntity> userPermissionEntities = userPermissionMapper.queryLimitUserPermissionByUserIds(getSetKey(unionUserRoleEntities));
        return ResponseUtil.setE(ResponseEnum.OK).setData(FormatUserRoleData.checkLimitPermission(userPermissionEntities, unionUserRoleEntities));
    }

    @GetMapping("/queryByEnabled")
    public ResponseUtil queryByEnabled(@RequestParam boolean enabled) {
        if (ObjectUtil.isEmpty(enabled)) return ResponseUtil.setE(ResponseEnum.OK);
        HashSet<UnionUserRoleEntity> hashSet = FormatUserRoleData.formatUserRole(userRoleMapper.selectAllUserRole(null, null, enabled));
        List<UserPermissionEntity> userPermissionEntities = userPermissionMapper.queryLimitUserPermissionByUserIds(getSetKey(hashSet));
        return ResponseUtil.setE(ResponseEnum.OK).setData(FormatUserRoleData.checkLimitPermission(userPermissionEntities, hashSet));
    }

    @Transactional
    @PostMapping("/editUserPermission")
    public ResponseUtil editUserPermission(@RequestBody EditUserPermissionEntity entity) {
        ArrayList<UserPermissionEntity> list = new ArrayList<>();
        for (String per : entity.getEditPermission()) {
            UserPermissionEntity userPermissionEntity = new UserPermissionEntity();
            userPermissionEntity.setUserId(entity.getUserId());
            userPermissionEntity.setPermissionId(per);
            list.add(userPermissionEntity);
        }

        try {
            LambdaQueryWrapper<UserPermissionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserPermissionEntity::getUserId, entity.getUserId());
            userPermissionService.remove(lambdaQueryWrapper);
            userPermissionService.saveBatch(list);
            return ResponseUtil.setE(ResponseEnum.OK).setMsg("权限修改成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("权限修改失败, 请刷新重试");
        }
    }
}
